<template>
  <el-form ref="jcszFormRef" :model="jcszform" :rules="rules" label-width="80px" size="normal">
    <el-form-item label="模版名称" prop="jhTemplateName">
      <el-input v-model="jcszform.jhTemplateName" placeholder="请输入模版名称"/>
    </el-form-item>
    <el-form-item label="商家编码" prop="jhCode">
      <el-input v-model="jcszform.jhCode" placeholder="请输入商家编码" disabled/>
    </el-form-item>
    <h5 style="padding-left: 12px">可用参数：{源商品ID}{货号}{年}{月}{日}{3位随机数}</h5>
    <el-form-item label="运费模版" prop="jhFreightTemplate">
      <el-select
        v-model="jcszform.jhFreightTemplate"
        placeholder="请选择模版"
        style="width: 100%">
        <el-option
          v-for="item in jhFreightTemplateOptions"
          :key="item.template_id"
          :label="item.name"
          :value="item.template_id">
        </el-option>
      </el-select>
    </el-form-item>
<!--    <el-form-item label="采购的" prop="jhPurchaseAddress">-->
<!--      &lt;!&ndash;      <el-input v-model="jcszform.jhPurchaseAddress" placeholder="请输入采购的"/>&ndash;&gt;-->
<!--      <el-select v-model="jcszform.jhPurchaseAddress">-->
<!--        <el-option v-for="dict in dict.type.jh_purchase_address" :key="dict.value" :label="dict.label" :value="dict.value" placeholder="中国内地（大陆）">{{ dict.label }}</el-option>-->
<!--      </el-select>-->
<!--    </el-form-item>-->
<!--    <el-form-item label="发货地" prop="jhShippingAddress">-->
<!--      <el-select v-model="jcszform.jhShippingAddress">-->
<!--        <el-option v-for="dict in dict.type.jh_shipping_address" :key="dict.value" :label="dict.label" :value="dict.value" placeholder="中国内地">{{ dict.label }}</el-option>-->
<!--      </el-select>-->
<!--    </el-form-item>-->
    <h3 style="padding-left: 12px">标题设置</h3>
    <div style="display: flex">
      <el-form-item label="添加前缀" prop="jhPrefixJc" style="margin-right: 10px;">
        <el-input v-model="jcszform.jhPrefixJc" maxlength="10" placeholder="请输入前缀" show-word-limit disabled style="width: 150px"/>
      </el-form-item>
      <el-form-item label="添加后缀" prop="jhSuffixJc">
        <el-input v-model="jcszform.jhSuffixJc" maxlength="10" placeholder="请输入后缀" show-word-limit disabled style="width: 150px"/>
      </el-form-item>
    </div>
    <div v-for="(pair, index) in jcszform.findReplacePairs" :key="pair.key" style="display: flex; align-items: center;">
      <el-form-item :prop="'findReplacePairs.' + index + '.templateFind'" label="查找内容" style="margin-right: 10px;">
        <el-input v-model="pair.templateFind" maxlength="10" placeholder="要替换的内容" show-word-limit disabled style="width: 150px"/>
      </el-form-item>
      <el-form-item :prop="'findReplacePairs.' + index + '.templateReplace'" label="替换成为" style="margin-right: 10px;">
        <el-input v-model="pair.templateReplace" maxlength="10" placeholder="新内容，留空则为删除" show-word-limit disabled style="width: 150px"/>
        <el-button
          class="custom-add-btn"
          icon="el-icon-plus"
          size="small"
          style="margin-left: 10px;"
          @click="addFindReplacePair"
        ></el-button>
        <el-button
          v-if="jcszform.findReplacePairs.length > 1"
          class="custom-remove-btn"
          icon="el-icon-minus"
          size="small"
          style="margin-left: 10px;"
          @click.prevent="removeFindReplacePair(pair)"
        ></el-button>
      </el-form-item>
    </div>
    <el-form-item label="价格" prop="jhPrice">
      <el-input v-model.number="jcszform.jhPrice" placeholder="请输入数值" type="number" step="0.1"/>
    </el-form-item>
    <el-form-item label="删除内容">
      <el-input
        v-model="jcszform.jhDelContent"
        :min-height="192"
        autosize
        disabled
        style="width: 531px; height: 200px"
        type="textarea"
      />
    </el-form-item>
  </el-form>
</template>

<script>
import {getShopFreightTemplate} from "@/api/jihuo/template";

export default {
  dicts: ['jh_purchase_address', 'jh_shipping_address'],
  name: "JhTemplateForm",
  data() {
    return {
      jcszform: {
        jhTemplateName: '',    // 新增
        jhCode: '',            // 新增
        jhPurchaseAddress: '', // 新增
        jhShippingAddress: '', // 新增
        jhPrefixJc: '',        // 新增
        jhSuffixJc: '',        // 新增
        jhDelContent: '',      // 新增
        jhFreightTemplate : '',
        findReplacePairs: [{
          templateFind: '',
          templateReplace: '',
          key: Date.now()
        }]
      },
      rules: {
        jhRevision: [
          {required: true, message: "乐观锁不能为空", trigger: "blur"}
        ],
        jhCreatedBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        jhCreatedTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        jhUpdatedBy: [
          {required: true, message: "更新人不能为空", trigger: "blur"}
        ],
        jhUpdatedTime: [
          {required: true, message: "更新时间不能为空", trigger: "blur"}
        ],
        jhTemplateName: [
          {required: true, message: "模版名称不能为空", trigger: "blur"}
        ],
        // jhCode: [
        // jhCode: [
        //   {required: true, message: "商家编码不能为空", trigger: "blur"}
        // ]
      },
      jhFreightTemplateOptions: [],
    }
  },
  mounted() {
    getShopFreightTemplate()
      .then(response => {
        if (response.data){
          this.jhFreightTemplateOptions = response.data
        }
      }).catch(error => {console.log(error)})
  },
  methods: {
    // 优化setData方法用于接收父组件数据
    setData(form) {
      // 使用Vue.set或直接赋值新对象确保响应式更新
      this.$nextTick(() => {
        // 先清空当前数据，避免旧数据残留
        this.jcszform = {
          ...this.jcszform,
          jhTemplateName: form.jhTemplateName || '',
          jhCode: form.jhCode || '',
          jhPurchaseAddress: form.jhPurchaseAddress || '',
          jhShippingAddress: form.jhShippingAddress || '',
          jhPrefixJc: form.jhPrefixJc || '',
          jhPrice: form.jhPrice || '',
          jhFreightTemplate: String(form.jhFreightTemplate || ''),
          jhSuffixJc: form.jhSuffixJc || '',
          jhDelContent: form.jhDelContent || ''
        };

        // 解析查找替换对
        if (form.jhTemplateFind && form.jhTemplateReplace) {
          try {
            const findArr = JSON.parse(form.jhTemplateFind) || [];
            const replaceArr = JSON.parse(form.jhTemplateReplace) || [];
            this.jcszform.findReplacePairs = findArr.map((find, index) => ({
              templateFind: find || '',
              templateReplace: replaceArr[index] || '',
              key: Date.now() + index // 确保每个对象有唯一key
            }));
          } catch (error) {
            console.warn('解析查找替换对失败:', error);
            this.jcszform.findReplacePairs = [{
              templateFind: '',
              templateReplace: '',
              key: Date.now()
            }];
          }
        } else {
          this.jcszform.findReplacePairs = [{
            templateFind: '',
            templateReplace: '',
            key: Date.now()
          }];
        }

        // 强制更新组件
        this.$forceUpdate();
      });
    },
    // 新增reset方法以解决父组件调用问题
    reset() {
      this.jcszform = {
        findReplacePairs: [{
          templateFind: '',
          templateReplace: '',
          key: Date.now()
        }]
      };
    },
    getFormData() {
      const findArray = this.jcszform.findReplacePairs.map(pair => {
        return pair.templateFind.trim() || null; // 空字符串转null
      });
      const replaceArray = this.jcszform.findReplacePairs.map(pair => {
        return pair.templateReplace.trim() || null; // 空字符串转null
      });

      // 检查是否有有效数据（至少有一个非null值）
      const hasValidFind = findArray.some(f => f !== null);
      const hasValidReplace = replaceArray.some(r => r !== null);
      return {
        ...this.jcszform,
        jhTemplateFind: hasValidFind ? JSON.stringify(findArray) : null,
        jhTemplateReplace: hasValidReplace ? JSON.stringify(replaceArray) : null
      };
    },
    // 新增方法：添加替换对
    addFindReplacePair() {
      this.jcszform.findReplacePairs.push({
        templateFind: '',
        templateReplace: '',
        key: Date.now()
      });
    },
    // 新增方法：移除替换对
    removeFindReplacePair(pair) {
      const index = this.jcszform.findReplacePairs.indexOf(pair);
      if (index !== -1) {
        this.jcszform.findReplacePairs.splice(index, 1);
      }
    }
  }
}
</script>

<style scoped>
/* 新增样式：移除按钮边框 */
.custom-add-btn,
.custom-remove-btn {
  border: none !important;
}

/* 处理悬停状态 */
.custom-add-btn:hover,
.custom-remove-btn:hover {
  border: none !important;
  background-color: #f5f7fa; /* 保持原有hover效果但无边框 */
}
</style>
